package fileutils

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"go/build"
	"os"
	"path/filepath"
	"strings"
)

func GetPkgPath(pkgPath string) (string, error) {
	pkg, err := GetPkg(pkgPath)
	return pkg.Dir, err
}
func GetPkg(pkgPath string) (*build.Package, error) {
	pkg, err := build.Default.Import(pkgPath, "", build.FindOnly)
	return pkg, err
}

// 获取第三方包下所有文件的相对路径
func GetPkgAllFilesPath(pkgPath string) ([]string, error) {
	pkg, err := build.Default.Import(pkgPath, "", build.FindOnly)
	logrus.Info(pkg.Dir)

	if err != nil {
		return nil, err
	}

	var paths []string
	err = filepath.Walk(pkg.Dir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.IsDir() {
			relPath, err := filepath.Rel(pkg.Dir, path)
			if err != nil {
				return err
			}
			paths = append(paths, relPath)
		}
		return nil
	})
	if err != nil {
		return nil, err
	}

	return paths, nil
}

func demo() {
	paths, err := GetPkgAllFilesPath("github.com/gin-gonic/gin")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	for _, path := range paths {
		fmt.Println(strings.TrimPrefix(path, "src/"))
	}
	logrus.Info(GetPkgPath("github.com/gin-gonic/gin"))
}
